package com.threeonemeeting.activity;

import java.io.File;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.snda.lib.http.HttpUtil;
import com.snda.lib.http.ICallBack;
import com.snda.lib.http.TaskManager;
import com.snda.lib.ui.MessageBox;
import com.snda.lib.util.FileHelper;
import com.snda.lib.util.ImageHelper;
import com.snda.lib.util.IntentHelper;
import com.threeonemeeting.Const;
import com.threeonemeeting.DataCenter;
import com.threeonemeeting.R;
import com.threeonemeeting.tab.BaseTabActivity;
import com.threeonemeeting.tab.MultiActivityTab;
import com.threeonemeeting.task.HttpConst;
import com.threeonemeeting.task.SendCommentsTask;
import com.threeonemeeting.util.MiscUtil;

public class SendCommentActivity extends BaseTabActivity implements ICallBack {
	private ProgressDialog loadingDialog;

	private int nMeetingId = 0;
	private int nTopicId = 0;

	private String strAttachImagePath = null;

	private PopupWindow mPopupWindow = null;

	// 当前Activity的实例
	private static SendCommentActivity mInstance = null;

	public static SendCommentActivity getInstance() {
		return mInstance;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_send_comment);
		MiscUtil.setBackBtnListener(this);

		mInstance = this;

		nMeetingId = getIntent().getExtras().getInt("eid");
		nTopicId = getIntent().getExtras().getInt("tid");

		// 发送评论
		final EditText editComments = (EditText) findViewById(R.id.editComment);

		Button btnSend = (Button) findViewById(R.id.btnSendComments);
		if (btnSend != null) {
			btnSend.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					String strText = editComments.getText().toString();
					if (strText.equals("") == true || strText == null) {
						MessageBox.showToast(SendCommentActivity.this
								.getApplicationContext(), "不能提交空评论哦，写点内容吧!");
						return;
					}

					MultiActivityTab parent = (MultiActivityTab) SendCommentActivity.this
							.getParent();
					loadingDialog = MessageBox.showProcessDlg(parent,
							"正在提交评论，请稍候...");
					loadingDialog.show();

					// 提交评论内容
					SendCommentsTask sendTask = new SendCommentsTask(
							SendCommentActivity.this, SendCommentActivity.this);

					if (strAttachImagePath != null
							&& strAttachImagePath.equalsIgnoreCase("") == false) {
						if (FileHelper.isExistFile(strAttachImagePath) == true) {
							sendTask.setUploadFile(strAttachImagePath);
						}
					}

					Bundle params = new Bundle();
					params.putString("eid", String.valueOf(nMeetingId));
					params.putString("tid", String.valueOf(nTopicId));
					params.putString("uid", String.valueOf(DataCenter
							.getInstance().currentLoginUserInfo.nUserId));
					params.putString(
							"pass",
							DataCenter.getInstance().currentLoginUserInfo.strPassword);
					params.putString("content", strText);
					TaskManager.addTask(sendTask, params, false);
				}

			});
		}

		// 从媒体库中分享
		final OnClickListener selectGalleryBtnListener = new OnClickListener() {

			public void onClick(View v) {

				MultiActivityTab tabActivity = getParentTab();
				Intent intent = IntentHelper.getImageFileIntent();
				tabActivity.startActivityForResult(intent,
						Const.RequestCode.IMAGEPICK_REQUEST_CODE);

				mPopupWindow.dismiss();
			}
		};

		// 即拍即传
		final OnClickListener selectCaremaBtnListener = new OnClickListener() {

			public void onClick(View v) {
				MultiActivityTab tabActivity = getParentTab();

				Intent intent = IntentHelper.getCameraIntent();
				tabActivity.startActivityForResult(intent,
						Const.RequestCode.CAMERA_REQUEST_CODE);

				mPopupWindow.dismiss();
			}
		};

		// 从SD卡中分享
		final OnClickListener selectSDBtnListener = new OnClickListener() {

			public void onClick(View v) {
				MultiActivityTab tabActivity = getParentTab();

				Intent intent = new Intent(SendCommentActivity.this,
						SelectImageFromSDActivity.class);
				intent.putExtra("type", "png|jpg|jpeg|bmp|gif|");
				tabActivity.startActivityForResult(intent,
						Const.RequestCode.SHAREFROMSD_REQUEST_CODE);

				mPopupWindow.dismiss();
			}
		};

		// 插入图片
		Button btnAddPicture = (Button) findViewById(R.id.btnAddPics);
		if (btnAddPicture != null) {
			btnAddPicture.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
					View shareView = mLayoutInflater.inflate(
							R.layout.lib_selimagewin, null);
					mPopupWindow = new PopupWindow(shareView,
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					mPopupWindow.showAtLocation(findViewById(R.id.btnAddPics),
							Gravity.CENTER, 0, 0);

					Button btnSelectFromMedia = (Button) shareView
							.findViewById(R.id.btnSelectFromMedia);
					Button btnSelectFromSD = (Button) shareView
							.findViewById(R.id.btnSelectFromSD);
					Button btnSelectFromCamera = (Button) shareView
							.findViewById(R.id.btnSelectFromCamera);
					Button btnClose = (Button) shareView
							.findViewById(R.id.btnClose);

					btnSelectFromMedia
							.setOnClickListener(selectGalleryBtnListener);
					btnSelectFromSD.setOnClickListener(selectSDBtnListener);
					btnSelectFromCamera
							.setOnClickListener(selectCaremaBtnListener);

					btnClose.setOnClickListener(new OnClickListener() {
						public void onClick(View v) {
							if (mPopupWindow != null) {
								mPopupWindow.dismiss();
							}
						}

					});
				}

			});
		}

		// 关闭按钮
		Button btnClose = (Button) findViewById(R.id.btnClose);
		if (btnClose != null) {
			btnClose.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					RelativeLayout attachImageLayout = (RelativeLayout) findViewById(R.id.layout_attach_image);
					attachImageLayout.setVisibility(View.GONE);

					strAttachImagePath = null;
				}

			});
		}

		/**
		 * 返回
		 */
		Button btnBack = (Button) findViewById(R.id.back);
		if (btnBack != null) {
			btnBack.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					if (mPopupWindow != null) {
						mPopupWindow.dismiss();
					}
					back();
				}
			});
		}

	}

	@Override
	public void back() {

		if (mPopupWindow != null) {
			if (mPopupWindow.isShowing() == true) {
				mPopupWindow.dismiss();
				return;
			}
		}

		super.back();
	}

	@Override
	protected void onStop() {
		super.onStop();

		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
		}
	}

	private void onSelectImage(String strPath) {
		String strPrefix = "file://";
		if (strPath.substring(0, strPrefix.length())
				.equalsIgnoreCase(strPrefix) == true) {
			strPath = strPath.substring(strPrefix.length(), strPath.length());
		}

		strAttachImagePath = strPath;

		ImageView imageView = (ImageView) findViewById(R.id.toAddedImage);
		if (imageView == null)
			return;

		Bitmap bm = ImageHelper.fittableDecodeFromPath(strPath);
		if (bm == null)
			return;

		Drawable dw = ImageHelper.getResourceDrawable(strPath);
		if (dw == null)
			return;

		RelativeLayout attachImageLayout = (RelativeLayout) findViewById(R.id.layout_attach_image);
		attachImageLayout.setVisibility(View.VISIBLE);

		imageView.setBackgroundDrawable(dw);

		// 文件大小
		long nFileSize = 0;
		TextView txSize = (TextView) findViewById(R.id.image_size);
		try {
			File imageFile = new File(strPath);
			nFileSize = imageFile.length();
			txSize.setText("大小：" + FileHelper.getSizeDesc(nFileSize));
		} catch (Exception e) {
			txSize.setText("大小：" + "无法获取");
		}

		TextView txDimension = (TextView) findViewById(R.id.image_dimensions);
		txDimension.setText("尺寸：" + bm.getWidth() + "x" + bm.getHeight());

		bm.recycle();
	}

	private void onSelectImageFromGallery(Intent data) {
		Uri selectedImage = data.getData();
		if (selectedImage == null)
			return;

		String strImagePath = selectedImage.toString();
		if (strImagePath == null)
			return;

		onSelectImage(strImagePath);
	}

	private void onSelectImageFromSD(Intent data) {
		Bundle bundle = data.getExtras();
		if (bundle != null) {
			String strPath = bundle.getString("path");
			if (strPath == null)
				return;

			onSelectImage(strPath);
		}
	}

	private void onSelectImageFromCamera(Intent data) {
		String strPath = data.getDataString();
		if (strPath != null) {
			String strPrefix = "file://";
			if (strPath.substring(0, strPrefix.length()).equalsIgnoreCase(
					strPrefix) == true) {
				strPath = strPath.substring(strPrefix.length(),
						strPath.length());
			}

			onSelectImage(strPath);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {

		case Const.RequestCode.SHAREFROMSD_REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				onSelectImageFromSD(data);
			}
			break;

		case Const.RequestCode.IMAGEPICK_REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				onSelectImageFromGallery(data);
			}

			break;

		case Const.RequestCode.CAMERA_REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				onSelectImageFromCamera(data);
			}

			break;

		}
	}

	public void doCallBack(Map<String, Object> mapData) {
		if (loadingDialog != null) {
			loadingDialog.dismiss();
		}

		Integer msgType = (Integer) mapData.get(HttpConst.KEY_TASK_TYPE);
		if (msgType == null) {
			Log.d(Const.Tag, "can't find type in response type");
			return;
		}

		Integer nError = (Integer) mapData.get(HttpUtil.KEY_ERROR_CODE);
		if (nError == null || nError != HttpUtil.ERROR_SUCCESS) {
			Log.d(Const.Tag, "response return error:" + nError + " type:"
					+ msgType);
			return;
		}

		if (msgType != HttpConst.TASKTYPE_SENDCOMMENTS) {
			return;
		}

		Boolean bSuccess = (Boolean) mapData.get("result");
		if (bSuccess == null) {
			MessageBox.showToast(getApplicationContext(), "评论失败");
			return;
		}

		MessageBox.showToast(getApplicationContext(), "评论成功");

		Bundle b = new Bundle();
		b.putInt("id", nMeetingId);
		b.putBoolean("refresh", true);
		startActivity("MeetingDetailActivity", "MeetingCommentsListActivity", b);
	}
}
